<template>
  <el-popover placement="top-start" :title="props.popoverTitle" :width="props.popoverWidth" trigger="click"
    :show-arrow="false" @show="handleShow" @hide="handleHide" ref="editPopoverRef">
    <div class="edit-popover-content">
      <el-input v-model="currentSort" :maxlength="props.inputMaxLength" :placeholder="props.inputPlaceholder"
        @input="handleInputFilter" @keyup.enter="handleSubmit" autofocus />
      <div class="btn-group">
        <el-button size="small" @click="handleCancel">取消</el-button>
        <el-button size="small" type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </div>
    <template #reference>
      <div class="table-edit-trigger">
        <span>
          {{ props.rowData.sort }}
        </span>
        <span class="edit-icon" :class="{ 'always-visible': props.displayMode === 'always' }">
          <SvgIcon name="ele-EditPen" :size="props.iconSize" />
        </span>
        <span class="edit-icon" :class="{ 'always-visible': props.displayMode === 'always' }">
          <el-icon :size="props.iconSize">
            <EditPen />
          </el-icon>
        </span>
      </div>
    </template>
  </el-popover>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { ElMessage, ElPopover } from "element-plus";

// 定义显示方式枚举
type DisplayMode = 'hover' | 'always';

// 定义接口，增强类型安全
interface TableRowData {
  sort: string | number; // 当前排序值
  [key: string]: any; // 允许其他行数据字段
}

// 父组件传递的 props：新增所有可配置字段，均带默认值
const props = defineProps<{
  rowData: TableRowData; // 表格当前行数据
  displayMode?: DisplayMode; // 图标显示方式：hover（默认）/ always
  popoverTitle?: string; // 弹出框标题（默认：排序编码）
  popoverWidth?: number | string; // 弹出框宽度（默认：200）
  inputMaxLength?: number; // 输入框最大长度（默认：20）
  inputPlaceholder?: string; // 输入框占位符（默认：请输入排序编码（字母/数字））
  iconSize?: number; // 图标大小（默认：16）
}>();

console.log(props.iconSize);
// 向父组件 emits 修改后的行数据
const emit = defineEmits<{
  (e: "confirmEdit", rowData: TableRowData): void;
}>();

// 弹出框实例引用
const editPopoverRef = ref<InstanceType<typeof ElPopover> | null>(null);
// 输入框当前值（与行数据解耦）
const currentSort = ref<string>("");

// 设置默认值（props 未传递时使用）
const defaultProps = {
  popoverTitle: "排序编码",
  popoverWidth: 200,
  inputMaxLength: 20,
  inputPlaceholder: "请输入排序编码（字母/数字）",
  iconSize: 16,
  displayMode: "hover" as DisplayMode,
};

// 弹出框显示时：同步当前排序值到输入框
const handleShow = () => {
  currentSort.value = String(props.rowData.sort || "");
};

// 弹出框隐藏时：重置输入框
const handleHide = () => {
  currentSort.value = "";
};

// 过滤输入：只允许字母、数字
const handleInputFilter = () => {
  currentSort.value = currentSort.value.replace(/[\W]/g, "");
};

// 取消修改
const handleCancel = () => {
  editPopoverRef.value?.hide();
};

// 提交修改
const handleSubmit = () => {
  const trimedSort = currentSort.value.trim();
  if (!trimedSort) {
    ElMessage.error("排序编码不能为空！");
    return;
  }

  const updatedRow = { ...props.rowData, sort: trimedSort };
  emit("confirmEdit", updatedRow);
  ElMessage.success("排序编码修改成功！");
  editPopoverRef.value?.hide();
};

// 监听行数据变化，同步输入框
watch(
  () => props.rowData.sort,
  (newVal) => {
    currentSort.value = String(newVal || "");
  }
);
</script>

<style scoped lang="scss">
.table-edit-trigger {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 4px;
  padding: 2px 4px;
  border-radius: 4px;
  transition: background-color 0.2s;

  &:hover {
    background-color: #f5f7fa;
    cursor: pointer;
  }
}

.edit-icon {
  opacity: 0;
  transition: opacity 0.2s;
  color: #409eff;
}

.edit-icon.always-visible {
  opacity: 1 !important;
}

.table-edit-trigger:hover .edit-icon:not(.always-visible) {
  opacity: 1;
}

.edit-popover-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 8px 0;
}

.btn-group {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>